#include "QtWidgetsApplication1.h"
#include <ranges>

#define WM_LOADEDDATA (WM_USER + 1)

QtWidgetsApplication1::QtWidgetsApplication1(QDialog* parent)
    : QDialog(parent)
    , ui(new Ui::QtWidgetsApplication1Class)
	, m_lastInputData{
	20,
	10000,
	5,
	0,
	0,
	true,
	}
{
    ui->setupUi(this);
    initView();
    initConnectEvent();
}

QtWidgetsApplication1::~QtWidgetsApplication1()
{
	if (m_loadData.joinable())
		m_loadData.join();
}

bool QtWidgetsApplication1::loadUrl(const QString& url)
{
    if (url.isEmpty() || !m_qMiniBlink) {
        return false;
    }
    return m_qMiniBlink->load(url);
}

void QtWidgetsApplication1::initView()
{
    m_qMiniBlink = new QMiniBlink;
    QGridLayout *gridLayout = new QGridLayout(this);
    ui->horizontalLayout->addWidget(m_qMiniBlink);
}

void QtWidgetsApplication1::initConnectEvent()
{
    wkeJsBindFunction("initData", jsInitData, this, 0);
    wkeJsBindFunction("onOk", jsOnOk, this, 1);
    wkeJsBindFunction("onCancel", jsOnCancel, this, 0);
    wkeJsBindFunction("loadData", jsLoadData, this, 0);

	connect(this, &QtWidgetsApplication1::loadedData, this, &QtWidgetsApplication1::onLoadedData);
}

jsValue WKE_CALL_TYPE QtWidgetsApplication1::jsInitData(jsExecState es, void* vptr)
{
	auto* pDlg = static_cast<QtWidgetsApplication1*>(vptr);
	const std::string json = xpack::json::encode(pDlg->m_lastInputData);
	return jsString(es, json.c_str());
}

jsValue WKE_CALL_TYPE QtWidgetsApplication1::jsOnOk(jsExecState es, void* vptr)
{
	auto* pDlg = static_cast<QtWidgetsApplication1*>(vptr);
	if (jsArgCount(es) != 1)
		return jsUndefined();
	auto value = jsArg(es, 0);
	auto type = jsTypeOf(value);
	if (!jsIsString(value))
		return jsUndefined();
	const auto* szTitle = jsToTempString(es, value);
	xpack::json::decode(szTitle, pDlg->m_formData);
	pDlg->onBtnOKClicked();
	return jsUndefined();
}

jsValue WKE_CALL_TYPE QtWidgetsApplication1::jsOnCancel(jsExecState es, void* vptr)
{
	auto* pDlg = static_cast<QtWidgetsApplication1*>(vptr);
	pDlg->onBtnCancelClicked();
	return jsUndefined();
}

jsValue WKE_CALL_TYPE QtWidgetsApplication1::jsLoadData(jsExecState es, void* vptr)
{
	auto* pDlg = static_cast<QtWidgetsApplication1*>(vptr);
	pDlg->loadData();
	return jsUndefined();
}
void QtWidgetsApplication1::onBtnCancelClicked()
{
	reject();
}

void QtWidgetsApplication1::onBtnOKClicked()
{
	accept();
}

void QtWidgetsApplication1::loadData()
{
	m_loadData = std::thread([this]() -> void {
		for (auto i : std::views::iota(0))
		{
			using namespace std::chrono_literals;
			std::this_thread::sleep_for(1ms);
			if (i == 500)
				break;
		}
		emit loadedData(10000);
		});
}

void QtWidgetsApplication1::onLoadedData(double data)
{
	auto js = std::format("window.loadedData({});", data);
	m_qMiniBlink->runJs(js.c_str());
}